<?php

class Upload
{
	//配置
	public $config = [
		'root' => './upload',
		'allow'=>['jpg','png','gif'],
		'max_size'=>1000000
	];
	//错误相关信息
	public $error =[
		'1' =>'文件大小比php.ini中upload_max_filesize指定值要大',
		'2' =>'文件的小比表单的MAX_FILE_SIZE指定的值大',
		'3' => '文件上传不完整（可能因为请求时间过长被终止）',
		'4' => '没有文件随着这个请求上传',
		'6' => '在php.ini中没有指定临时文件夹'
	];

	public $file;//上传文件的相关信息

	public $errorInfo = '';//存储错误信息

	public $suffix ; //存储文件的后缀
	
	/**
	 * [__construct 构造函数]
	 * @param array $config [description]
	 */
	public function __construct($config=array())
	{
		$this->config = array_merge($this->config,$config);
	}
	/**
	 * [__get 魔术方法，获取未定义属性]
	 * @param  [type] $name [description]
	 * @return [type]       [description]
	 */
	public function __get($name)
	{
		return $this->config[$name];
	}

	/**
	 * [save 外部调用的save]
	 * @return [type] [description]
	 */
	public function save()
	{
		$this->file = current($_FILES);
		// $this->file['error'] = 2;
		if(!$this->checkEeror()) return false;

		if(!$this->checkType()) return false;

		if(!$this->checkSize()) return false;

		return $this->move();
	}
	/**
	 * [checkEeror 检测错误]
	 * @return [type] [description]
	 */
	protected function checkEeror()
	{
		if($this->file['error']>0){
			$this->errorInfo = $this->error[$this->file['error']];
			return false;
		}
		return true;
	}
	/**
	 * [checkType 检测类型]
	 * @return [type] [description]
	 */
	protected function checkType()
	{
		$suffixArr = explode('.', $this->file['name']);

		$this->suffix =  end($suffixArr);

		// $this->suffix = 'txt';

		// var_dump($this->file['name']);
		if(!in_array($this->suffix,$this->allow)){
			$this->errorInfo ="上传的类型不允许，允许类型为".implode(",",$this->allow);
			return false;
		}

		return true;
	}
	/**
	 * [checkSize 检测大小]
	 * @return [type] [description]
	 */
	protected function checkSize()
	{
		if($this->file['size']>$this->max_size){
			$this->errorInfo ="上传的大小不允许，允许大小为".$this->max_size;
			return false;
		}

		return true;
	}
	/**
	 * [move 移动文件]
	 * @return [type] [description]
	 */
	protected function move()
	{	
		//创建目录
		is_dir($this->root) || mkdir($this->root);
		//生成文件名
		$name = uniqid().mt_rand(1000,9999).".".$this->suffix;

		$path = $this->root.'/'.$name;

		$res = move_uploaded_file($this->file['tmp_name'],$path);

		if($res){
			return $path;
		}else{
			$this->errorInfo = "移动文件失败";
			return false;
		}
	}
}
